<template>
    <div class="flex">
        <Tree
            :title="treeTitle"
            @selectTree="selectTree"
            :treeData="treeData"
        />
        <div class="table" style="width: 100%">
            <Search
                :sjy="sjy"
                :formState="formState"
                @searchData="onSearchList"
            />
            <a-card>
                <TableTools
                    :hasSelected="hasSelected"
                    :selectId="removeId"
                    :hasSelectedModify="hasSelectedModify"
                    @modify="onModify"
                    @del="onToolsDel"
                    @addData="onAddData"
                />
                <a-table
                    class="ant-table-striped"
                    size="small"
                    :row-selection="{
                        selectedRowKeys: selectedRowKeys,
                        onChange: onSelectChange,
                    }"
                    :pagination="{
                        pageSize: formState.pageSize,
                        total: total,
                        showTotal: (total) => `共${total}条记录`,
                        size: 'middle',
                    }"
                    :rowClassName="
                        (record, index) =>
                            index % 2 === 1 ? 'table-striped' : null
                    "
                    :rowKey="(record) => record.id"
                    :columns="columns"
                    :data-source="repositories"
                    :loading="tableLoading"
                    @change="handleTableChange"
                >
                    <template #sjdxms="{ text: row }">
                        <SnippetsOutlined />
                        {{ row.sjdxms }}
                    </template>
                    <template #sjdxlx="{ text: row }">
                        <a-tag color="red">{{ dataType(row.sjdxlx) }}</a-tag>
                    </template>
                    <template #ywlxmc="{ record }">
                        {{
                            record.ywlxmc
                                ? record.ywlxmc
                                : onHandleCode(record.ywlxid)
                        }}
                    </template>
                    <template #operation="{ text: row, index }">
                        <a-space>
                            <a-button size="small" @click="onEdit(row)"
                                >编辑</a-button
                            >
                            <a-popconfirm
                                title="你确定删除这条数据?"
                                ok-text="确认"
                                cancel-text="取消"
                                @confirm="onDel(row.id, index)"
                            >
                                <a-button size="small">删除</a-button>
                            </a-popconfirm>
                            <a-button size="small" @click="onSetField(row.id)"
                                >配置字段</a-button
                            >
                            <a-button size="small" @click="onPreview(row.id)"
                                >预览</a-button
                            >
                        </a-space>
                    </template>
                </a-table>
            </a-card>
            <ModalC
                v-if="visible"
                :visible="visible"
                :loading="loading"
                :title="title"
                :row="row"
                :type="type"
                :userList="userList"
                :tableNameList="tableNameList"
                :dataSource="dataSource"
                :createColumns="createColumns"
                :sjy="sjy"
                @handleOk="onHandleConfirm"
                @handleCancel="onHandleCancel"
            />
        </div>
    </div>
</template>

<script lang="ts">
import {
    defineComponent,
    reactive,
    toRefs,
    onMounted,
    UnwrapRef,
    createVNode,
} from "vue";
import { TableStateFilters } from "ant-design-vue/es/table/interface";
import * as API from "@/api/data-object";
import { getData } from "@/api/index";
import {
    SnippetsOutlined,
    ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import useRepositoryNameSearch from "./useRepositoryNameSearch";
import useRepositoryTable from "./useRepositoryTable";
import ModalC from "@/components/modal/ModalC.vue";
import Tree from "@/components/tree/TreeG.vue";
import TableTools from "./components/tableTools.vue";
import Search from "./components/search.vue";
import { message, Modal } from "ant-design-vue";
import custom from "@/api/use-data";
import { onHandleCode } from "@/filter/index";
interface FormState {
    sjyid: string;
    ywlxid: string;
    sjdxmc: string;
    sjdxms: string;
    sjylx: string;
    sjyfl: string;
    pageSize: number;
    pageNum: number;
    orderByColumn: string;
    isAsc: string;
}
interface Store {
    treeTitle: string;
    tableLoading: boolean;
    loading: boolean;
    visible: boolean;
    title: String;
    row: UnwrapRef<Record<string, any>>;
    type: number;
    userList: [];
    tableNameList: [];
    dataSource: any[];
    createColumns: any[];
    sjy: any[];
    onSearchList: (formState: FormState) => void;
    onModify: () => void;
    onToolsDel: () => void;
    onAddData: () => void;
    handleTableChange: (
        pagination: any,
        filter: TableStateFilters,
        sorter: any
    ) => void;
    onHandleConfirm: (form: any) => void;
    onHandleCancel: () => void;
    onEdit: (row: any) => void;
    onDel: (id: string, index: number) => void;
    onSetField: (id: string) => void;
    onPreview: (id: string) => void;
    dataType: (type: string) => void;
    selectTree: (type: string) => void;
}
export default defineComponent({
    name: "DataObject",
    setup() {
        const formState = reactive<FormState>({
            sjyid: "",
            ywlxid: "",
            sjdxmc: "",
            sjdxms: "",
            sjylx: "",
            sjyfl: "",
            pageSize: 10,
            pageNum: 1,
            orderByColumn: "",
            isAsc: "asc",
        });
        const columns = [
            {
                title: "数据表中文名",
                slots: { customRender: "sjdxms" },
                key: "sjdxms",
            },
            { title: "数据表名称", dataIndex: "sjdxmc", key: "sjdxmc" },
            {
                title: "业务类型",
                slots: { customRender: "ywlxmc" },
                key: "ywlxmc",
            },
            {
                title: "数据对象类型",
                slots: { customRender: "sjdxlx" },
                key: "sjdxlx",
            },
            { title: "所属数据源分类", dataIndex: "sjyfl", key: "sjyfl" },
            { title: "所属数据源类型", dataIndex: "sjylx", key: "sjylx" },
            { title: "所属数据源名称", dataIndex: "sjymc", key: "sjymc" },
            { title: "所属用户", dataIndex: "ssyh", key: "ssyh" },
            { title: "创建人", dataIndex: "username", key: "username" },
            { title: "创建时间", dataIndex: "time", key: "time", sorter: true },
            {
                title: "操作",
                key: "operation",
                slots: { customRender: "operation" },
            },
        ];
        const {
            total,
            repositories,
            getUserRepositories,
        } = useRepositoryNameSearch(formState);
        onMounted(() => {
            getUserRepositories();
            getData({}).then(({ rows }: any) => {
                store.sjy = rows;
            });
        });
        const {
            state,
            hasSelected,
            onSelectChange,
            hasSelectedModify,
        } = useRepositoryTable();
        const store = reactive<Store>({
            treeTitle: "数据源信息",
            tableLoading: false,
            loading: false,
            visible: false,
            title: "",
            type: 1,
            row: {},
            userList: [],
            tableNameList: [],
            dataSource: [],
            createColumns: [],
            sjy: [],
            onSearchList: (formState) => {
                store.tableLoading = true;
                formState = formState;
                getUserRepositories().then(() => {
                    store.tableLoading = false;
                });
            },
            onModify: () => {
                store.onEdit(state.currItem);
            },
            onToolsDel: () => {
                getUserRepositories();
            },
            onAddData: () => {
                store.loading = false;
                store.visible = true;
                store.title = "添加数据";
                store.type = 4;
            },
            // page切换
            handleTableChange: (pagination, filter, sorter) => {
                store.tableLoading = true;
                formState.pageNum = pagination.current;
                if (sorter && sorter.order) {
                    formState.isAsc =
                        sorter.order === "ascend" ? "asc" : "desc";
                    formState.orderByColumn = sorter.field;
                }
                getUserRepositories().then(() => {
                    store.tableLoading = false;
                });
            },
            //弹框确认
            onHandleConfirm: (form) => {
                store.loading = true;
                // type 1：编辑 2：配置字段 3：数据预览 4:添加数据
                switch (store.type) {
                    case 1:
                        API.edit(form).then(({ msg }: any) => {
                            getUserRepositories();
                            store.loading = false;
                            store.visible = false;
                            message.success(msg);
                        });
                        break;
                    case 2:
                        if (form.kjzd || form.sjzd) {
                            Modal.confirm({
                                content: "再次配置字段会重新建表，请谨慎操作！",
                                icon: createVNode(ExclamationCircleOutlined),
                                onOk() {
                                    API.saveColumnApi(form.dataSource).then(() => {
                                            getUserRepositories();
                                            store.loading = false;
                                            store.visible = false;
                                            message.success("操作成功");
                                        }
                                    );
                                    // API.dataObjectApi(form).then(
                                    //     ({ msg }: any) => {
                                    //         getUserRepositories();
                                    //         store.loading = false;
                                    //         store.visible = false;
                                    //         message.success(msg);
                                    //     }
                                    // );
                                },
                                onCancel() {
                                    store.loading = false;
                                    Modal.destroyAll();
                                },
                            });
                        } else {
                            store.loading = false;
                            store.visible = false;
                            message.info("请选择需要配置的字段！");
                        }
                        break;
                    case 4:
                        API.addData(form).then(({ msg }: any) => {
                            getUserRepositories();
                            store.loading = false;
                            store.visible = false;
                            message.success(msg);
                        });
                        break;
                    default:
                        break;
                }
            },
            //关闭弹窗
            onHandleCancel: () => {
                store.loading = false;
                store.visible = false;
            },
            //编辑
            onEdit: (row) => {
                store.row = row;
                store.loading = false;
                store.visible = true;
                store.title = "修改数据";
                store.type = 1;
                API.schemaList(row.sjyid).then(({ items }: any) => {
                    store.userList = items;
                });
                API.tableOrViewList(row.sjyid, row.ssyh, row.sjdxlx).then(
                    ({ items }: any) => {
                        store.tableNameList = items;
                    }
                );
            },
            //删除
            onDel: (id, index) => {
                API.remove(id).then(({ msg }: any) => {
                    repositories.value.splice(index, 1);
                    message.success(msg);
                    getUserRepositories();
                });
            },
            onSetField: (id) => {
                const hide = message.loading("正在请求数据...");
                API.setField(id).then(({ data }: any) => {
                    hide();
                    store.dataSource = data;
                    store.loading = false;
                    store.visible = true;
                    store.title = "分配数据字段";
                    store.type = 2;
                });
            },
            //预览
            onPreview: (id) => {
                const hide = message.loading("正在请求数据...");
                API.dataPreview(id).then(({ data }: any) => {
                    hide();
                    store.createColumns = [];
                    store.dataSource = [];
                    for (let i = 0; i < data.keySet.length; i++) {
                        const e = data.keySet[i];
                        let createObject = Object.assign({
                            title: e,
                            dataIndex: e,
                            key: e,
                        });
                        store.createColumns.push(createObject);
                    }
                    for (let t = 0; t < data.dataList.length; t++) {
                        const x = data.dataList[t];
                        const createID: never[] = Object.assign(x, {
                            customId: t,
                        });
                        store.dataSource.push(createID);
                    }
                    store.loading = false;
                    store.visible = true;
                    store.title = "数据预览";
                    store.type = 3;
                });
            },
            dataType: (type) => {
                let text = "";
                switch (type) {
                    case "01":
                        text = "数据表";
                        break;
                    default:
                        break;
                }
                return text;
            },
            selectTree: (type) => {
                formState.sjylx = type;
                getUserRepositories();
            },
        });
        return {
            total,
            formState,
            repositories,
            columns,
            onSelectChange,
            hasSelected,
            hasSelectedModify,
            ...toRefs(state),
            ...toRefs(store),
            treeData: custom.treeData,
            onHandleCode,
        };
    },
    components: {
        SnippetsOutlined,
        Search,
        TableTools,
        ModalC,
        Tree,
    },
});
</script>
<style lang="less" scoped>
.ant-table-striped :deep(.table-striped) {
    background-color: #fafafa;
}
</style>